HTML5 Canvas绘制椭圆越来越多

时间:2013-04-30 03:51:44

标签: javascript html5 canvas drawing

我正在使用HTML5绘图在白板上书写。 问题是当我试图绘制椭圆时,按下并拖动,绘制了许多椭圆。

ctx.moveTo(startX, startY + (y-startY)/2);
ctx.bezierCurveTo(startX, startY, x, startY, x, startY + (y-startY)/2);
ctx.bezierCurveTo(x, y, startX, y, startX, startY + (y-startY)/2);
ctx.stroke();

我想每次只显示一个椭圆。 有帮助吗?

1 个答案:

答案 0 :(得分:0)

这可能会有所帮助 - 这是我使用弧和缩放绘制椭圆的版本。

https://jsfiddle.net/richardcwc/wdf9cocz/

//Canvas
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//Variables
var scribble_canvasx = $(canvas).offset().left;
var scribble_canvasy = $(canvas).offset().top;
var scribble_last_mousex = scribble_last_mousey = 0;
var scribble_mousex = scribble_mousey = 0;
var scribble_mousedown = false;

//Mousedown
$(canvas).on('mousedown', function(e) {
    scribble_last_mousex = parseInt(e.clientX-scribble_canvasx);
	scribble_last_mousey = parseInt(e.clientY-scribble_canvasy);
    scribble_mousedown = true;
});

//Mouseup
$(canvas).on('mouseup', function(e) {
    scribble_mousedown = false;
});

//Mousemove
$(canvas).on('mousemove', function(e) {
    scribble_mousex = parseInt(e.clientX-scribble_canvasx);
	scribble_mousey = parseInt(e.clientY-scribble_canvasy);
    if(scribble_mousedown) {
        ctx.clearRect(0,0,canvas.width,canvas.height); //clear canvas
        //Save
        ctx.save();
        ctx.beginPath();
        //Dynamic scaling
        var scalex = 1*((scribble_mousex-scribble_last_mousex)/2);
        var scaley = 1*((scribble_mousey-scribble_last_mousey)/2);
        ctx.scale(scalex,scaley);
        //Create ellipse
        var centerx = (scribble_last_mousex/scalex)+1;
        var centery = (scribble_last_mousey/scaley)+1;
        ctx.arc(centerx, centery, 1, 0, 2*Math.PI);
        //Restore and draw
        ctx.restore();
        ctx.strokeStyle = 'black';
        ctx.lineWidth = 5;
        ctx.stroke();
    }
    //Output
    $('#output').html('current: '+scribble_mousex+', '+scribble_mousey+'<br/>last: '+scribble_last_mousex+', '+scribble_last_mousey+'<br/>mousedown: '+scribble_mousedown);
});
canvas {
    cursor: crosshair;
    border: 1px solid #000000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="800" height="500"></canvas>
<div id="output"></div>