HTML5 Canvas背景图自适应铺满屏幕宽高 - 已解决图片模糊问题

3 篇文章 0 订阅
2 篇文章 0 订阅

这里提供的是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);
}

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

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

土拨鼠的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值