To use the code to achieve a number of external images and text merge, but also to upload to seven cattle cloud , Then share the image link through the client . The picture background needs to support user-defined replacement .

Implementation scheme

In a canvas Called many times on drawImage function , They are drawn separately on canvas in , Many times later canvas This is the effect of merging multiple images , Then call toDataURL Function will canvas Turn into dataURL Format picture , then dataURL Change the format to blob file , Upload to Qi Niu Yun .

The pit that needs attention

canvas The problem of blurred image synthesis

take canvas The length and width of is set to the style length and width 2 Times or more , as follows :

var canvas = document.getElementById("myCanvas");

canvas.width = "600";

canvas.height = "600" = "300px" = "300px"

Report security error

If your picture url Not in the same domain as the page , Calling toDataURL Function will report a security error .chrome in :

Uncaught SecurityError: Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported.

Safari It seems to be more strict , If the root domain name is the same and the subdomains are different, an error will still be reported :

Cross-origin image load denied by Cross-Origin Resource Sharing policy.

reason :

Shanghai Web Xiao Bian, a training institution, thinks that analyzing the causes of problems is better than any successful case , This is canvas The top priority of image synthesis . No, CORS Although authorization can be done in canvas Using images in , But doing so will pollute (taints) canvas . as long as canvas The contaminated , You can no longer extract data from the canvas , That is to say, you can no longer call toBlob(), toDataurl(/81014/cooperation/pentest/) and getImageData() Other methods , Otherwise, a security error will be thrown (security error). This is actually to protect the user's personal information , Avoid unauthorized remote web The site loads the user's image information , Causing privacy leaks .

resolvent :

Here in Shanghai Web Training institutions think it is the key part , So I also brought the code . Create a new... For each picture img object , And then give it src Equal parameter , In this way, we have to wait until img After loading canvas Other operating , stay img Of load In the event handler , Otherwise, empty content may be drawn .

let img = new Image()

img.setAttribute('crossorigin', 'anonymous')


img.onload = function () {

// do Something


img.error = function () {}

canvas Picture synthesis , stay mac and pc It's working well on your browser , But in ios11 The following mobile phones cannot toDataURL

terms of settlement 1:

Change the way images are loaded , First in DOM Newly built img label , as follows :

Be careful :crossOrigin="Anonymous" Must be in src Attribute before

utilize js obtain img Elements

var img = document.getElementById('bgImg')

ctx.drawImage(img, 0, 0, 700, 700)

canvas.toBlob() safari The invalid

terms of settlement 2:

take canvas Use toDataURL Method to base64, then base64 adopt file API To blob

function dataURLtoBlob (dataurl) { // take dataUrl To Blob

let arr = dataurl.split(',')

let mime = arr[0].match(/:(.*?);/)[1]

let bstr = atob(arr[1])

let n = bstr.length

let u8arr = new Uint8Array(n)

while (n--) {

u8arr[n] = bstr.charCodeAt(n)


return new Blob([u8arr], {type: mime})

}var resultBase64 = canvas.toDataurl('/81014/cooperation/pentest/image/jpeg') // To jpeg Compress image size var canvasBlob = dataURLtoBlob(resultBase64)

canvas More articles about pits in image synthesis

  1. JS Watermark image synthesis example page

    CSS Code : .clip { position: absolute; clip: rect(0 0 0 0); } HTML Code : <input type="file" id ...

  2. Mobile canvas Text image synthesis and image generation (canvas Width adaptive mobile screen )

    This is a code that I did before about the composition of text and picture , For your reference , We need to be considerate of insufficient expenditure : Specific comments are included in the code , If you don't understand, you can leave a message and communicate with each other .<!DOCTYPE html> <html lang=& ...

  3. Canvas Realize image synthesis and download composite image

    Now we often encounter that kind of promotion picture with two-dimensional code , As shown in the figure below : 1 It's the background of the whole map ,2 It's a two-dimensional code . The background of this image remains the same , The two-dimensional code inside is changing . So we need to generate the QR code separately and combine it with the background . We can go through can ...

  4. Html5 Canvas Realize image synthesis

    Combine multiple images into one <!doctype html> <html> <head> <meta charset="utf-8"> < ...

  5. Android DIY The way ( One ) Multi image composition in specified area Zoom in narrow Mirror image rotate etc. ( turn )

    Let's see the renderings first // Pay attention to the template function The location is provided by the background data , Here we use fake data 4 A little bit perhaps xy Add a region as an example  // At first, our company used a transparent cover Operation picture But found There are many limitations . Later, it directly restricted the area ...

  6. vue + canvas Watermark the picture

    Ideas : Draw two pictures into one The goal is : Input text , Draw on the picture , Simple implementation of image watermarking effect : Input text 1: ‘ Guess what ’ + picture 2 = picture 3( Don't look at the button to clear the watermark , I'm rubbish Not realized ) Select Picture html & ...

  7. canvas Picture drag rotation 2 ——canvas State of preservation (save and restore)

    introduction In the last post “canvas Drag and rotate one of the pictures ” in , I have a deep understanding of coordinate transformation , But drag and drop rotation using only coordinate transformation , Will change canvas The state of the coordinate system , This affects the drawing of other elements on the canvas . therefore , It's time to ...

  8. android Text image synthesis

    quote : The two methods : 1. Write directly on the picture String str = "PIC ...

  9. Java The image processing ( One ) Picture synthesis

    How to make multiple avatars similar QQ The head of the group ? As shown in the figure above , How to use java Combine a single image into a group portrait . In a square frame , To combine multiple pictures into the above pictures . The first thing to do is , According to the degree of intersection of circles , Calculate the space between the center of the circle and the picture ...

Random recommendation

  1. *cf.4 greedy

    D. Kostya the Sculptor time limit per test 3 seconds memory limit per test 256 megabytes input stand ...

  2. 《Linux And safety 》 practice 3.3

    <Linux And safety > Practice three Character set summary and Analysis [by lwr] One .ISO.UCS/UTF.GB Series character set analysis 1. Character set & Character encoding Character set (Charset): It's all that one system supports ...

  3. C++ Self study program

    Course description Course name :C++ The voyage of the expedition &C++ Departure of the expedition The name of the instructor :james_yuan Course link address C++ The voyage of the expedition C++ Departure of the expedition Chapter list Choose the reason At the beginning, I was more familiar with the network ...

  4. Da Xian said Android studio Realization Service AIDL

    Today, we need to use AIDL Call to , Previously used eclipse There are a lot of tutorials , It's very convenient to use , Now it's just changed Android studio, Undeniable? studio It's really powerful , It's just that many functions need to be explored . AIDL(And ...

  5. Linux mint Under the development settings

    Switch thinpad Home-Pgup End-Pgdn sudo vim ~/.Xmodmap keysym Prior = Home keysym Next = End Disable the paste function in the middle of the mouse su ...

  6. cf932d On the tree

    Answer link I feel like I can do , But I'm not very familiar with it , Back again

  7. maven install No sign problems found

    I can't find the wrong information in the newspaper javax.servlet package . This is tomcat Internal jar package . But I build path Look, it's added tomcat Of .. Last in pom.xml Add dependency <depend ...

  8. Python And rrdtool The combination module of

    rrdtool(round robin database) The tool is the storage format of ring database ,round robin It's a technique that processes quantitative data and pointers to current elements .rrdtool It is mainly used to track the changes of objects , Generate these ...

  9. Nginx SSL To configure

    One .SSL principle ① client ( browser ) Send a https Request to server ② The server needs a set of certificates , It's actually public key and private key , This set of certificates can be generated by itself , You can also apply to the organization , The server will transfer the public key to the client ③ Client received ...

  10. How to view the current project Laya The engine version of

    Open the project and enter... In the debug console Laya.version