这里提供的是vue版本的Canvas实例,如需要其它版本可自行更改

template

<canvas ref="myCanvas"></canvas>

data

data() {
	return {
		rowHeight: '',
		rowWidth: ''
	}
},

mounted

mounted() {
	this.rowHeight = this.$refs.row.clientHeight;	// 屏幕高度(我这里是自己写的一个div容器,可以自行更改)
	this.rowWidth = this.$refs.row.clientWidth;	// 屏幕宽度
	this.init()
}

methods

init() {
	let _this = this;
	setTimeout(function () {	// 延迟执行,避免页面还没加载完成报错
		let canvas = _this.$refs.myCanvas;
		let ctx = canvas.getContext("2d");
		// 设置显示大小(css像素)
		canvas.style.width = _this.rowWidth + "px";
		canvas.style.height = _this.rowHeight + "px";
		// 设置内存中的实际大小(缩放以考虑额外的像素密度)
		let scale = window.devicePixelRatio;	// 在视网膜屏幕上更改为 1 以查看模糊的画布
		canvas.width = Math.floor(_this.rowWidth * scale);
		canvas.height = Math.floor(_this.rowHeight * scale);
		// 标准化坐标系以使用 css 像素
		ctx.scale(scale, scale);
		let img = new Image();
		img.src = require('../../../static/img/home/background.jpg');
		img.onload = function () {
		let w = img.width;	// 图片宽度
		let h = img.height;	// 图片高度
		let conW = _this.rowWidth;	// 页面宽度
		let conH = _this.rowHeight;	// 页面高度
		let dw = conW / w;	//canvas与图片的宽高比
		let dh = conH / h;	
		// 裁剪图片中间部分
		if (w > conW && h > conH || w < conW && h < conH) {
			if (dw > dh) {
				ctx.drawImage(img, 0, (h - conH / dw) / 2, w, conH / dw, 0, 0, conW, conH)
			} else {
				ctx.drawImage(img, (w - conW / dh) / 2, 0, conW / dh, h, 0, 0, conW, conH)
			}
		} else {	// 拉伸图片
			if (w < conW) {
				ctx.drawImage(img, 0, (h - conH / dw) / 2, w, conH / dw, 0, 0, conW, conH)
			} else {
				ctx.drawImage(img, (w - conW / dh) / 2, 0, conW / dh, h, 0, 0, conW, conH)
				}
			}
		}
	}, 500);
}

插入图片模糊的问题已有说明,点击立即前往

Logo

前往低代码交流专区

更多推荐