我需要在HTML画布中绘制圆圈,圆圈的大小取决于用户拖动鼠标的数量。
但是我期望的结果有所不同。我已经附加了脚本文件。
var canvas=document.getElementById('myCanvas');
canvas.addEventListener('mousedown',down);
canvas.addEventListener('mouseup',up);
canvas.addEventListener('mousemove',function(e){
var mousePos=getMousePos(canvas,e);
var posx=mousePos.x;
var posy=mousePos.y;
drawCircle(posx,posy,canvas)
});
var md;
function down(){
md=true;
}
function up(){
md=false;
}
function getMousePos(canvas,e){
var pos=canvas.getBoundingClientRect();
return {
x:e.clientX-pos.left,
y:e.clientY-pos.top
}
}
function drawCircle(x,y,canvas){
var ctx=canvas.getContext('2d');
var radius=x/10;
if(md){
ctx.beginPath();
ctx.arc(100, 75,radius, 0, 2 * Math.PI);
ctx.stroke();
}
}
#myCanvas {width:100%; height:600px}
<canvas id="myCanvas"></canvas>
答案 0 :(得分:0)
使用画布绘制时,必须记住需要清除画布或将其还原为较旧的状态,否则笔触只会不断堆积。
您可以在此处了解有关画布状态的更多信息:https://www.tutorialspoint.com/html5/canvas_states.htm
student_class
var canvas=document.getElementById('myCanvas');
canvas.addEventListener('mousedown',down);
canvas.addEventListener('mouseup',up);
canvas.addEventListener('mousemove',function(e){
var mousePos=getMousePos(canvas,e);
var posx=mousePos.x;
var posy=mousePos.y;
drawCircle(posx,posy,canvas)
});
var md;
function down(){
md=true;
}
function up(){
md=false;
}
function getMousePos(canvas,e){
var pos=canvas.getBoundingClientRect();
return {
x:e.clientX-pos.left,
y:e.clientY-pos.top
}
}
function drawCircle(x,y,canvas){
var ctx=canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
var radius=x/10;
if(md){
ctx.beginPath();
ctx.arc(100, 75,radius, 0, 2 * Math.PI);
ctx.stroke();
}
}
#myCanvas {width:100%; height:600px}