简体   繁体   中英

CSS/JavaScript: issue when styling canvas (for mouse drawing)

I have this simple code for drawing with mouse in canvas. But if I try to style the canvas, like altering the width or centering, the pointer and line drawn get separated. How do I solve this?

JavaScript:

var el = document.getElementById('canvas');
var ctx = el.getContext('2d');
var isDrawing;

el.onmousedown = function(e) {
  isDrawing = true;
  ctx.moveTo(e.clientX, e.clientY);
};
el.onmousemove = function(e) {
  if (isDrawing) {
    ctx.lineTo(e.clientX, e.clientY);
    ctx.stroke();
  }
};
el.onmouseup = function() {
  isDrawing = false;
};

HTML:

CSS:

canvas { 
    border: 2px solid #ccc;
    padding-left: 0;
    padding-right: 0;
    margin-left: auto;
    margin-right: auto;
    display: block;
    width: 800px;
}

Here's a Fiddle

NEVER set canvas's width / height using css. It's really a bad idea. Always use the native width / height property of the canvas.

Also, you should probably be using e.offsetX and e.offsetY to get the x and y coordinates of the mouse.

Here's a working fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM