使用Canvas绘制图案出现位置偏离怎么办,如何避免
Admin 2022-07-01 群英技术资讯 1510 次浏览
这篇文章给大家分享的是使用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进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章主要介绍了CSS3 mask 遮罩的具体使用方法,详细的介绍了CSS3 mask 遮罩的具体使用,具有一定的参考价值,有兴趣的可以了解一下
这篇文章主要介绍了css display:box 新属性的相关资料,需要的朋友可以参考下
篇文章给大家分享的是DIV自适应高度自动补充剩余高度的实现。小编觉得挺实用的,因此分享给大家做个参考,文中示例代码介绍的非常详细,感兴趣的朋友接下来一起跟随小编看看吧。
今天给大家分享一个圣杯布局和双飞翼布局及他们之间的区别,这两个三行布局一直是一些大厂前端面试的高频考点,带你走进大厂面试题,活不多说,
方法:1、利用“元素{animation:名称 时间}”语句给元素绑定动画;2、利用“@keyframes 名称{100%{width:宽度值;}}”语句,设置元素改变宽度的动画动作,实现元素改变宽度的动画效果。
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
7x24小时售前:400-678-4567
7x24小时售后:0668-2555666
24小时QQ客服
群英微信公众号
CNNIC域名投诉举报处理平台
服务电话:010-58813000
服务邮箱:service@cnnic.cn
投诉与建议:0668-2555555
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 ICP核准(ICP备案)粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008