前端水印实现方式 All In One
前端水印实现方式 All In One
watermark
canvas to image
canvas.toDataURL(type, encoderOptions);
SVG & base64
function drawInlineSVG(ctx, rawSVG, callback) {
var svg = new Blob([rawSVG], {type:"image/svg+xml;charset=utf-8"}),
domURL = self.URL || self.webkitURL || self,
url = domURL.createObjectURL(svg),
img = new Image;
img.onload = function () {
ctx.drawImage(this, 0, 0);
domURL.revokeObjectURL(url);
callback(this);
};
img.src = url;
}
// usage:
drawInlineSVG(ctxt, svgText, function() {
console.log(canvas.toDataURL()); // -> PNG data-uri
});
https://stackoverflow.com/questions/27230293/how-to-draw-an-inline-svg-in-dom-to-a-canvas
Canvas toDataURL All In One
convert image to base64 in javascript
demo
solution ?
const userName = "xgqfrms";
const watermark = `
`
// const watermark = `
//
// `
const app = document.querySelector(`#app`);
app.insertAdjacentHTML('beforeend', watermark);
const svgElement = document.querySelector(`#svg`);
console.log(`svgElement =`, svgElement);
const svgURL = new XMLSerializer().serializeToString(svgElement);
console.log(`svgURL =`, svgURL);
// const imgSrc = `data:image/svg+xml; charset=utf8, ${encodeURIComponent(svgURL)}`;
// const imgSrc = `data:image/svg+xml; charset=utf8, ${window.btoa(svgURL)}`;
const imgSrc = `data:image/svg+xml;base64,${window.btoa(svgURL)}`;
console.log(`imgSrc =`, imgSrc);
// app.style.background = `left 5% / 15% 60% repeat url(${imgSrc})`;
app.style.background = `left 5% / 15% 60% repeat url(${imgSrc})`;
// app.style.background = `url(${imgSrc}) repeat`;
// app.style.backgroundImage = `url(${imgSrc})`;
// app.style.backgroundRepeat = `repeat`;
// app.style.backgroundPosition = `0 0`;
const img = document.querySelector(`#img`);
img.src = imgSrc;
const pre = document.querySelector(`#pre`);
pre.insertAdjacentText('beforeend', imgSrc);
// const canvas = document.getElementById("canvas");
// const ctx = canvas.getContext("2d");
// const dataURL = canvas.toDataURL();
// console.log(`dataURL =`, dataURL);
refs
https://stackoverflow.com/a/70863414/5934465
https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL
?xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有??xgqfrms, 禁止转载 ???,侵权必究??!