【发布时间】:2021-11-03 18:02:09
【问题描述】:
我正在尝试制作一个较长的绘图画布,但用户可以退出绘图模式并进入手动滚动模式,就像您通常在手机上滚动网站一样。
我正在考虑在画布的一侧添加一个滚动条。但是如果我们可以像在手机上阅读网站一样正常滚动画布会更好。
html,css代码:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="user-scalable=no,initial-scale=1.0,maximum-scale=1.0" />
<style>
.container {
margin: 10px;
overflow: scroll;
}
#main {border: 1px solid #0000ff; overflow: scroll;}
</style>
<script src="draw.js"></script>
</head>
<body>
<div class="container">
<button id="clear">clear button that will clear teh canvas</button><br>
<canvas id="main" width="250" height="1000"></canvas>
</div>
</body>
</html>
触摸绘图的javascript代码:
window.onload = function() {
document.ontouchmove = function(e){ e.preventDefault(); }
var canvas = document.querySelector('#main');
// const width = canvas.width = window.innerWidth;
// const height = canvas.height = window.innerHeight;
var canvastop = canvas.offsetTop;
var context = canvas.getContext("2d");
var lastx;
var lasty;
context.strokeStyle = "#000000";
context.lineCap = 'round';
context.lineJoin = 'round';
context.lineWidth = 5;
function clear() {
context.fillStyle = "#ffffff";
context.rect(0, 0, 300, 300);
context.fill();
}
function dot(x,y) {
context.beginPath();
context.fillStyle = "#000000";
context.arc(x,y,1,0,Math.PI*2,true);
context.fill();
context.stroke();
context.closePath();
}
function line(fromx,fromy, tox,toy) {
context.beginPath();
context.moveTo(fromx, fromy);
context.lineTo(tox, toy);
context.stroke();
context.closePath();
}
canvas.ontouchstart = function(event){
event.preventDefault();
lastx = event.touches[0].clientX;
lasty = event.touches[0].clientY - canvastop;
dot(lastx,lasty);
}
canvas.ontouchmove = function(event){
event.preventDefault();
var newx = event.touches[0].clientX;
var newy = event.touches[0].clientY - canvastop;
line(lastx,lasty, newx,newy);
lastx = newx;
lasty = newy;
}
var clearButton = document.getElementById('clear')
clearButton.onclick = clear
clear()
}
【问题讨论】:
标签: javascript html css canvas scrollbar