怎么禁止下载图片(midjourney实现)
方案一:禁止右键
html
<img src="image.png" oncontextmenu="return false;" />
js
window.onload = function () {
document.oncontextmenu = function (event) {
event.returnValue = false
}
}
方案二:禁止拖拽
html
<img src="image.png" ondragstart="return false;" />
方案三:使用遮罩层
html
<div style="position: relative; display: inline-block">
<img src="image.png" alt="" />
<div
style="
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 10;
background: url(image.png) no-repeat center center / contain;
opacity: 0.7;
"
></div>
</div>
方案四:转换为 canvas
ts
export async function imageToCanvas(url, canvas) {
return new Promise((resolve, reject) => {
// 新建Image对象,引入当前目录下的图片
const img = new Image()
img.src = url
const c = canvas.getContext('2d')
// 图片初始化完成后调用
img.onload = function () {
// 将canvas的宽高设置为图像的宽高
canvas.width = img.width
canvas.height = img.height
// canvas画图片
c.drawImage(img, 0, 0, img.width, img.height)
resolve()
}
img.addEventListener('error', (e) => {
reject(e)
})
})
}
js
function throwFn() {
throw new Error(
'Uncaught DOMException: Failed to execute \'toDataURL\' on \'HTMLCanvasElement\': Tainted canvases may not be exported.',
)
}
const $canvasRef = useRef < HTMLCanvasElement > (null)
useEffect(() => {
;(async () => {
await imageToCanvas(props.url, $canvasRef.current)
$canvasRef.current.toBlob = throwFn
$canvasRef.current.toDataURL = throwFn
})()
}, [])
/* <canvas
ref={$canvasRef}
onTouchStart={preventDefaultListener}
onContextMenu={preventDefaultListener}
/> */