Z
Z
zooks2017-11-10 19:13:12
JavaScript
zooks, 2017-11-10 19:13:12

How to pass a default object parameter to a function in JavaScript?

We pass the width and height, if they are not set, then take them from the context object.
width = context.width, height = context.height

let canvas = document.getElementById('mycanvas'),
    ctx = canvas.getContext('2d');

    let drawGrid = (context, width = context.width, height = context.height) => {
        for (let x = 0.5; x < width; x += 10) {
            context.moveTo(x, 0);
            context.lineTo(x, height);
        }

        for (let y = 0.5; y < height; y += 10) {
            context.moveTo(0, y);
            context.lineTo(width, y);
        }
    }

        drawGrid(ctx); // чтобы можно было передать только один объект контекста
        ctx.lineWidth = 1;
        ctx.strokeStyle = '#eee';
        ctx.stroke();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2017-11-10
@zooks

And why not:

let drawGrid = (context) => {
        const width = context.width
        const height = context.height
        for (let x = 0.5; x < width; x += 10) {
            context.moveTo(x, 0);
            context.lineTo(x, height);
        }

        for (var y = 0.5; y < height; y += 10) {
            context.moveTo(0, y);
            context.lineTo(width, y);
        }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question