簡體   English   中英

我如何知道HTML5 Canvas何時完成繪圖?

[英]How can I know when HTML5 Canvas finished drawing?

我是javascript的初學者。 我正在嘗試在客戶端調整圖像大小,然后將它們上傳到我的服務器進行存儲我已經找到了使用HTML5 Canvas的方法: http//hacks.mozilla.org/2011/01/how-to-develop-一個-HTML5的圖像上載/

我的問題 :它繼續上傳空白圖片。 我認為空白圖像的原因是當我從畫布抓取圖像時畫布沒有完成繪圖。 當我從畫布抓取圖像之前設置3秒windows.timeout一切正常。 有沒有比超時更可靠的方法? 或者還有其他方法來進行客戶端圖像大小調整嗎?

我正在進行客戶端圖像大小調整的原因是因為我正在處理上傳不必要的大文件的人,我認為最有效的是調整客戶端圖像大小。

謝謝你的任何提示/答案!

 //resize image Resizeimage.resize(file); //***if i wrap this part with timeout it works var canvas = document.getElementById('canvas'); var data = canvas.toDataURL(file.type); // convert base64/URLEncoded data component to raw binary data held in a string var bytestring; if (data.split(',')[0].indexOf('base64') >= 0) bytestring = atob(data.split(',')[1]); else bytestring = escape(data.split(',')[1]); //get imagetype var mimeString = data.split(',')[0].split(':')[1].split(';')[0]; // write the bytes of the string to a typed array var ia = new Uint8Array(bytestring.length); for (var i = 0; i < bytestring.length; i++) { ia[i] = bytestring.charCodeAt(i); } // create a blob from array var blob = new Blob([ia], { type: mimeString }); //upload files $scope.upload = $upload.upload({ url: 'articles/imageUpload', method: 'POST', file: blob //update progress bar }).progress(function(event) { $scope.uploadInProgress = true; $scope.uploadProgress = Math.floor(event.loaded / event.total * 100); //file upload success }).success(function(data, status, headers, config) { $scope.uploadInProgress = false; $scope.uploadedImage = JSON.parse(data); $scope.isDisabled = false; //file upload fail }).error(function(err) { $scope.uploadInProgress = false; console.log('Error uploading file: ' + err.message || err); }); //*** 

 angular.module('articles').factory('Resizeimage', [ function() { var imgSelectorStr = null; // Resizeimage service logic function render(src) { var image = new Image(); image.onload = function() { var canvas = document.getElementById('canvas'); //check the greater out of width and height if (image.height > image.width) { image.width *= 945 / image.height; image.height = 945; } else { image.height *= 945 / image.width; image.width = 945; } //draw (&resize) image to canvas var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); canvas.width = image.width; canvas.height = image.height; ctx.drawImage(image, 0, 0, image.width, image.height); }; image.src = src; } function loadImage(src) { // Create fileReader and run the result through the render var reader = new FileReader(); reader.onload = function(e) { render(e.target.result); }; reader.readAsDataURL(src); } // Public API return { resize: function(src) { loadImage(src); return true; } }; } ]); 

你的問題很簡單。

只要你沒有附加到任何事件,JavaScript就會一個接一個地運行一個語句(並且你需要這個,因為你想要在抓取圖像時執行所有語句)。

如果將代碼附加到事件(例如image.onload ),則代碼的這一部分將等待事件,其余代碼將繼續異步。

所以你是對的 - 當你試圖抓住它時,不會繪制圖像。

通過超時(最低效/不安全)來解決它的糟糕風格通過將圖像抓取代碼包裝在函數中並在完成圖像重新調整大小后運行此函數來更好地解決這個問題。 它就像您用來同步異步事件的回調。

 /* setTimeout will behave like an event */ setTimeout( function(){ $('console').append("<div>SetTimeout</div>"); SynchCodeAfterTimeout(); }, 1000); AsynchCodeAfterTimeout(); function AsynchCodeAfterTimeout(){ $('console').append("<div>AsynchCodeAfterTimeout</div>"); } function SynchCodeAfterTimeout(){ $('console').append("<div>SynchCodeAfterTimeout</div>"); } 
 console{ font-family: Consolas, monaco, monospace; } 
 <script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script> <console></console> 

代碼示例

 render(); // Resizeimage service logic function render() { var image = new Image(); image.onload = function() { var canvas = document.getElementById('canvas'); //check the greater out of width and height if (image.height > image.width) { image.width *= 945 / image.height; image.height = 945; } else { image.height *= 945 / image.width; image.width = 945; } //draw (&resize) image to canvas var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); canvas.width = image.width; canvas.height = image.height; ctx.drawImage(image, 0, 0, image.width, image.height); /*timeout not needed its just there so the browser renders the canvas contents so you can see them when the alert pops up*/ setTimeout(function() { alert('yey all the drawing is done (this is synchronous)'); }); }; image.src = 'https://loremflickr.com/320/240'; } 
 <canvas id="canvas"></canvas> 

<script type="text/javascript">
     window.onload = function(){
         //Whatever you want to do when it has finished loading here
     }
</script>

您可以將這段代碼放在HTML中或JavaScript文件中的某個位置,然后不使用腳本標記;)

希望這適合你:D

我有一個問題,圖像畫布總是空白。

然后我拖延了,現在工作正常。

setTimeout(function () {
    var da = document.getElementById("canvasFabric").toDataURL("png", "1");
    $('#FInalImage').attr("src", canvasFabric.toDataURL("png", "1"));
    window.open(da);
}, 100);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM