Javascript [CANVAS]“减慢帧速率?”

问题描述 投票:0回答:1

你好吗?我正在为自己的代码遇到一个小问题。我被要求用javascript创建一个绘画程序,我快到了,但是我在努力绘画多快。我进行了绘画,以便在客户端x和y位置的每个mouseDrag事件上绘制一些内容。

Sample Paint

查看示例油漆的形状是如何定义的,您可以看到每个形状,这是在画布上绘制后的程序。

这里是我的,它画得太快了。

My Paint

if(dragging && type.options[type.selectedIndex].value == "squares") {
            ctx.lineTo(e.clientX, e.clientY);
            ctx.lineWidth = 5;        
            ctx.beginPath();
            ctx.rect(e.clientX, e.clientY, 40, 40);    
            ctx.fill();
            ctx.fillStyle = "yellow";
            ctx.beginPath();
            ctx.moveTo(e.clientX, e.clientY);
}
javascript html canvas paint
1个回答
0
投票

您可以节省每次抽奖的时间,并且每当有可能再次抽奖时,请检查自上次起是否经过了足够的时间。

这里是一个例子:

const ctx = document.getElementById('canvas').getContext('2d');
const speedInput = document.getElementById('draw-speed');
let buffer = +speedInput.value;
let lastPaint;

ctx.canvas.onmousemove = ({ x, y }) => {
    const now = Date.now();
    if (!lastPaint || (now - lastPaint) > buffer) {
        lastPaint = now;
        ctx.fillRect(x, y, 10, 10);
    }
}

speedInput.onchange = ({ target }) => { 
    buffer = +target.value; 
};
canvas {
    border: 1px solid black;
}
label {
    display: block;
}
<canvas id="canvas"></canvas>
<label for="draw-speed">Draw speed</label>
<select id="draw-speed">
    <option>0</option>
    <option>50</option>
    <option selected>100</option>
    <option>150</option>
</select>
© www.soinside.com 2019 - 2024. All rights reserved.