Paint canvas not working properly

南笙酒味 提交于 2019-12-25 02:41:13

问题


http://www.asifslab.com/reveal.js-master/Why%20does%20wind%20feel%20cold.html#/4 Why doesn't the drawing canvas work properly? The line drawn is away from the point clicked. However, if I use the canvas out of reveal.js it works perfectly. http://codepen.io/anon/pen/eEaKh Also when the erase function is run, it leaves a white border outside. How do I fix these problems?


回答1:


just change e.pageX to e.clientX and e.pageY to e.clientY because in your codepen account
canvas origin and page origin is almost at same place but in other it is not.




回答2:


To calculate the mouse position you need to subtract the position of the canvas:

Here is one way of doing this (inside the event handler):

var rect = canvas.getBoundingClientRect(),
    x = e.clientX - rect.left,
    y = e.clientY - rect.top;

Now your x and y will be relative to canvas.




回答3:


Here's a copy/pasta of a small part of my paint app. Notice I'm using offsets of the canvas in my calculations. I also have a zoom function that scales the canvas, so taking into account that I added it to the calculation of the mouse cursor.

$('canvas').mousemove(function(e) {
    // x and y are globals, x inits to null, mousedown sets x, mouseup returns x to null
    if (x==null) return;
    x = (100/$('#zoom').val())*(e.pageX - $(this).offset().left);
    y = (100/$('#zoom').val())*(e.pageY - $(this).offset().top);

    $('#debug').html(x+', '+y); // constantly update (x,y) position in a fixed div during debugging
});


来源:https://stackoverflow.com/questions/20757990/paint-canvas-not-working-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!