美文网首页web前端技术分享
canvas style width和canvas.width

canvas style width和canvas.width

作者: CRJ997 | 来源:发表于2021-03-26 13:44 被阅读0次

canvas style width 也就是canvas element style中设置的width属性的值。也就是css width:

<canvas style="width: 800px; height: 800px">your browser doesn't support canvas element</canvas>

canvas width也就是给canvas html width设置的值,也就是:

<canvas width="800px" height="800px">your browser doesn't support canvas element</canvas>

两者有什么区别呢?一句话概括就是:
style width决定在浏览器的大小表现。canvas html width决定canvas里面有多少个像素。
也就是,如果你想要一个2048*2048的画布,那么你要设置canvas的html width和height为2048。但是浏览器放不下这么大。咋办?这时候设置画布的style.width和style.height为800。就搞定了。

如果你想做画布点击选中功能

做画布点击选中图形的功能,那么主要的问题就是判断鼠标是不是点到了图形上。图形坐标是相对于画布左上角的,这时候需要把鼠标的坐标转化成画布上的坐标,然后判断鼠标是不是点到了图形上。当你的画布是20482048,style 是800800的时候(假设画布就在浏览器左上角),鼠标的坐标是基于style的,进行转换就是:
nextX = x * 2048 / 800;
nextY = y * 2048 / 800;
也就是:
nextX = x * cavasHtmlWidth / canvasStyleWidth;
nextY = y * canvasHtmlHeight / canvasStyleHeight;

因为假设就在浏览器左上角,所以鼠标的坐标不用减去画布相对于浏览器左上角的偏移量,如果画布不在浏览器左上角。那么鼠标的坐标需要减去画布相对于浏览器左上角的偏移量。偏移量可以用htmlElement.getBoundingClientRect(),取函数返回值的left和top就可以了。

相关文章

网友评论

    本文标题:canvas style width和canvas.width

    本文链接:https://www.haomeiwen.com/subject/cbyjhltx.html