<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>高清Canvas绘制</title>
<style>
body {
margin: 0;
padding: 20px;
display: flex;
flex-direction: column;
align-items: center;
background-color: #f5f5f5;
font-family: Arial, sans-serif;
}
canvas {
background-color: white;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
margin-bottom: 20px;
}
.controls {
margin-bottom: 20px;
}
a {
color: #0066cc;
text-decoration: none;
margin-top: 20px;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<h1>高清Canvas绘制示例</h1>
<div class="controls">
<button id="drawBtn">绘制图形</button>
<button id="clearBtn">清除画布</button>
</div>
<canvas id="highResCanvas"></canvas>
<script>
document.addEventListener('DOMContentLoaded', function() {
// 获取Canvas元素和上下文
const canvas = document.getElementById('highResCanvas');
const ctx = canvas.getContext('2d');
// 设置初始大小
const size = 500;
canvas.style.width = size + 'px';
canvas.style.height = size + 'px';
// 高清Canvas设置
function setupHighResCanvas() {
// 获取设备像素比
const dpr = window.devicePixelRatio || 1;
// 设置Canvas的实际大小(考虑像素比)
canvas.width = size * dpr;
canvas.height = size * dpr;
// 缩放上下文以匹配CSS大小
ctx.scale(dpr, dpr);
// 设置绘制样式
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
}
// 初始设置
setupHighResCanvas();
// 绘制函数
function draw() {
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制高清图形
ctx.save();
// 考虑到缩放,我们需要调整绘制坐标
const scale = window.devicePixelRatio || 1;
const adjustedSize = size / scale;
// 绘制渐变背景
const gradient = ctx.createLinearGradient(0, 0, adjustedSize, adjustedSize);
gradient.addColorStop(0, '#ff9a9e');
gradient.addColorStop(1, '#fad0c4');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, adjustedSize, adjustedSize);
// 绘制圆形
ctx.beginPath();
ctx.arc(adjustedSize/2, adjustedSize/2, adjustedSize/3, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
ctx.fill();
ctx.strokeStyle = '#333';
ctx.lineWidth = 4;
ctx.stroke();
// 绘制文字
ctx.font = '24px Arial';
ctx.fillStyle = '#333';
ctx.textAlign = 'center';
ctx.fillText('高清Canvas示例', adjustedSize/2, adjustedSize/2);
ctx.restore();
}
// 按钮事件
document.getElementById('drawBtn').addEventListener('click', draw);
document.getElementById('clearBtn').addEventListener('click', function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
// 初始绘制
draw();
// 窗口大小改变时重新设置Canvas
window.addEventListener('resize', function() {
setupHighResCanvas();
draw();
});
});
</script>
</body>
</html>
高清Canvas绘制
于 2025-05-13 16:20:13 首次发布