使用Canvas绘制图案出现位置偏离怎么办,如何避免
Admin 2022-07-01 群英技术资讯 1261 次浏览
这篇文章给大家分享的是使用Canvas绘制图案出现位置偏离怎么办,如何避免。小编觉得挺实用的,因此分享给大家做个参考,文中的介绍得很详细,而要易于理解和学习,有需要的朋友可以参考,接下来就跟随小编一起了解看看吧。使用 canvas 绘图时,指定的 div 大小一定不要超过该 div 所能获得的最大范围,否则绘制的点会跟实际位置发生偏离。
例如
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled 1</title>
<style type="text/css">
.style1 {
font-size: x-small;
}
</style>
</head>
<body >
<div style="margin:2%">
<div id="test" style="width:800px;height:800px;background-color:#cbdad0d9">
<canvas id="container" onmousemove="mousemove(event)" onmousedown="mousedown()" onmouseup="mouseup()"></canvas>
</div>
</div>
<script type="text/javascript">
var paint = false;
var start = false;
var canvas = document.getElementById("container");
canvas.width = 800;
canvas.height = 800;
var offsetY = canvas.offsetTop;
var offsetX = canvas.offsetLeft;
var y;
var x;
var context = canvas.getContext("2d");
function mousemove(e) {
if (paint == true){
if (start == false){
context.moveTo(0, 0);
start = true;
} else {
context.moveTo(x, y);
}
x = e.pageX - offsetX;
y = e.pageY - offsetY;
context.lineTo(x, y);
context.stroke();
}
}
function mousedown(event) {
paint = true;
console.log("down")
}
function mouseup(event) {
paint = false;
console.log("up")
}
</script>
</body>
</html>
上例中可以正确的绘制线图。
如果更改为:
<div style="margin:20%">
<div id="test" style="width:800px;height:800px;background-color:#cbdad0d9">
<canvas id="container" onmousemove="mousemove(event)" onmousedown="mousedown()" onmouseup="mouseup()"></canvas>
</div>
</div>
由于 canvas 所需 width 800px 无法满足,因此绘制线图时,与实际鼠标位置发生偏离。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
对于CSS怎样实现垂直居中的效果,我们之前也了解了很多方法,而不同的实现方法各有其优缺点,本文再给大家分享一个特别的CSS实现垂直居中的方法,感兴趣的朋友就继续往下看吧。
这篇文章主要介绍了纯css3实现横向无限滚动的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
CSS怎样实现浏览器的最小化还原和关闭按键?对于浏览器的最小化还原和关闭按键,大家应该很很熟悉的吧,也就是我们浏览器右上角的三个按键功能。今天我们就来了解看看,用CSS如何来实现这几个按钮,文中的示例代码介绍得很详细,有需要的朋友可以参考,接下来就跟随小编一起了解看看吧。
1. 相对定位1.1) 什么是相对定位相对定位:盒子可以根据自己原来的位置进行位置调整(通过位置描述词实现)。位置描述词:<br /> left: 向右移动; right 向左移动;top 向下移动;botto
这篇文章主要介绍了CSS3实现酷炫的3D旋转透视效果,代码简单易懂,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008