最近,我偶然發(fā)現(xiàn)了一個(gè)我無(wú)法克服的問(wèn)題。 我試圖在網(wǎng)站上編碼一個(gè)固定大小的畫布(400px x 400px ),但假設(shè)這個(gè)畫布有784像素(28px x 28px ),這樣我可以稍后將其轉(zhuǎn)換為numpy大小的數(shù)組(1,784)。 我試圖通過(guò)改變css、js或html中畫布的大小來(lái)做到這一點(diǎn)。目前我所知道的是,css只對(duì)& quot真實(shí)& quot畫布的大小,所以我希望我需要與js代碼的東西。
這是我的代碼
HTML:
<div class="field">
<canvas id="canvas" width="28" height="28" ></canvas>
</div>
JS:
const canvas = document.getElementById("canvas");
canvas.width = 400;
canvas.height = 400;
let context = canvas.getContext("2d");
context.fillStyle = "white";
context.fillRect(0,0,400,400);
console.log(canvas.clientHeight)
let draw_color = "black";
let draw_width = "14";
let is_drawing = false;
let start_background_color = "white";
canvas.addEventListener("touchstart",start,false);
canvas.addEventListener("touchmove",draw,false);
canvas.addEventListener("mousedown",start,false);
canvas.addEventListener("mousemove",draw,false);
canvas.addEventListener("touchend",stop,false);
canvas.addEventListener("mouseup",stop,false);
canvas.addEventListener("mouseout",stop,false);
function start(event){
is_drawing = true;
context.beginPath();
context.moveTo(event.clientX - canvas.offsetLeft,
event.clientY-canvas.offsetTop);
event.preventDefault();
}
function draw(event){
if(is_drawing){
context.lineTo(event.clientX - canvas.offsetLeft,
event.clientY-canvas.offsetTop)
context.strokeStyle = draw_color;
context.lineWidth = draw_width;
context.lineCap = "round";
context.lineJoin = "round";
context.stroke();
}
event.preventDefault();
}
function stop(event){
if(is_drawing){
context.stroke();
context.closePath();
is_drawing=false;
}
event.preventDefault();
}
CSS:
#canvas{
border:10px red;
cursor: pointer;
padding-left: 0;
padding-right: 0;
margin-left: auto;
margin-right: auto;
display: block;
margin-top: 100px;
margin-bottom: 0px;
}
.field{
padding: 10px 10px 10px 10px;
border: 10px red;
帆布照片