<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>canvas 宽高设置</title>
<style>
#canvas {
background-color: #f9f9f9;
/* 方式一(禁用):通过 css 设置,结果:画布内容会等比变形 */
/* height: 500px;
width: 500px; */
}
</style>
</head>
<body>
<canvas id="canvas">浏览器不支持 canvas </canvas>
</body>
<script>
//注意:当不给 canvas 画布设置宽高时,canvas 是有默认宽高的,width-300 height-150
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// 方式二(推荐):通过 js 设置,画布内容不变形,注意:此处无单位,实际单位是像素
canvas.height = 500
canvas.width = 500
function drawLine(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
drawLine(20, 20, 100, 100);
</script>
</html>
网友评论